﻿using System;
using System.Collections.Generic;
using System.Linq;
using Me.Practice.ElevatorEngine.Domain.Entity;

namespace Me.Practice.ElevatorEngine.Infrastructure
{
	internal class ElevatorCycle
	{
		private int _directionFactor;
		private readonly int _floorMaxNumber;
        private readonly int _floorMinNumber;
		private int _currentFloorNumber;
		
		public ElevatorCycle(int init)
		{
            _directionFactor = 1;

            _currentFloorNumber = BuildingContext.Floors.Single(f => f.Number == init).Number;
			
			_floorMaxNumber = BuildingContext.Floors.Max().Number;
		    _floorMinNumber = BuildingContext.Floors.Min().Number;
		}
		
		public int NextFloor()
		{
            _currentFloorNumber += _directionFactor;

            if (_currentFloorNumber == _floorMaxNumber && _directionFactor > 0)
                _directionFactor *= (-1);
            
            if(_currentFloorNumber == _floorMinNumber && _directionFactor < 0)
                _directionFactor *=(-1);

            return BuildingContext.Floors.Single(f => f.Number == _currentFloorNumber + _directionFactor).Number;
		}
	}
}
